package cn.nawang.ebeim.server.util;

import java.security.Timestamp;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

/**
 * @ClassName: JsonUtil
 * @Description: TODO
 * @author fanyb
 * @date Aug 17, 2015 11:46:33 AM
 * @version v1.0
 */
public class JsonUtil {
  private static final SerializerFeature[] features =
      {SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
          SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse,
          SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.UseISO8601DateFormat};

  private static SerializeConfig config = new SerializeConfig();

  private static final SerializerFeature[] featuresNumber = {SerializerFeature.WriteMapNullValue,
      SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullBooleanAsFalse,
      SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.UseISO8601DateFormat};

  static {
    config.put(java.util.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd"));
    config.put(java.sql.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd"));
    config.put(Timestamp.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
  }

  /**
   * 
   * @author fanyb
   * @Description: 转换成json格式字符串
   * @param object json对象
   * @return String 返回json格式字符串
   * @date Aug 17, 20154:59:37 PM
   *
   * @修改人
   * @修改日期
   */
  public static String toString(Object object) {
    return JSON.toJSONString(object, config, features);
  }

  public static String toStringAsNumberNull(Object object) {
    return JSON.toJSONString(object, config, featuresNumber);
  }

  /**
   * 
   * @author fanyb
   * @Description: json对象转换成列表对象
   * @param jsonText json对象
   * @param clazz 对象的class
   * @return List 列表（class对象的列表）
   * @date Aug 17, 20155:00:48 PM
   *
   * @修改人
   * @修改日期
   */
  public static List toList(String jsonText, Class clazz) {
    return JSON.parseArray(jsonText, clazz);
  }

  /**
   * 
   * @author fanyb
   * @Description: json对象转换成实体对象
   * @param jsonText json对象
   * @param clazz 对象的class
   * @return Object 实体对象（class的实体）
   * @date Aug 17, 20155:01:43 PM
   *
   * @修改人
   * @修改日期
   */
  public static Object toObject(String jsonText, Class clazz) {
    return JSON.parseObject(jsonText, clazz);
  }
}
